package org.pzy.springboot.service;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class WordImportService {

    public List<String[]> importWordWithTable(InputStream inputStream) throws IOException {
        List<String[]> data = new ArrayList<>();
        // 读取 Word 文档
        XWPFDocument document = new XWPFDocument(inputStream);
        // 获取文档中的所有表格
        List<XWPFTable> tables = document.getTables();
        if (tables.isEmpty()) {
            throw new IllegalArgumentException("No tables found in the document.");
        }
        // 处理第一个表格
        XWPFTable table = tables.get(0);
        for (XWPFTableRow row : table.getRows()) {
            String[] rowData = new String[row.getTableCells().size()];
            int cellIndex = 0;
            for (XWPFTableCell cell : row.getTableCells()) {
                rowData[cellIndex++] = cell.getText();
            }
            data.add(rowData);
        }
        return data;
    }
}